<template>
	<view class="contont">
		<nav-bar :title="pageInfo.navbarTitle" :iconLeft="true" />
		<view class="content-bgc">
			<view class="b-con">
				<uni-forms :model="form" :rules="rules" ref="refForm" label-width="100px">
					<uni-forms-item label="编号" name="code" required>
						<view style="display: flex;gap:20rpx">
							<uni-easyinput v-model="form.code" placeholder="请输入编号" class="iptBor" :inputBorder="false"
								:disabled="switchCode" />
							<view style="margin-left: 20rpx" v-show="pageInfo.type == 'add'">
								<u-switch v-model="switchCode" @change="switchChange" size="20" />
								自动生成
							</view>
						</view>
					</uni-forms-item>
					<uni-forms-item label="设备名称" name="name" required>
						<uni-easyinput v-model="form.name" placeholder="请输入设备名称" class="iptBor" :inputBorder="false" />
					</uni-forms-item>
					<uni-forms-item label="设备类型" name="classify" required>
						<uni-data-select v-model="form.classify" :localdata="classify_list" placeholder="请选择设备类型" mode="underline"
							:clear="false" />
					</uni-forms-item>
					<uni-forms-item label="设备品牌">
						<uni-easyinput v-model="form.brand" placeholder="请输入设备品牌" class="iptBor" :inputBorder="false" />
					</uni-forms-item>
					<uni-forms-item label="设备型号">
						<uni-easyinput v-model="form.model" placeholder="请输入设备型号" class="iptBor" :inputBorder="false" />
					</uni-forms-item>
					<uni-forms-item label="序列号SN">
						<uni-easyinput v-model="form.sn" placeholder="请输入序列号SN" class="iptBor" :inputBorder="false" />
					</uni-forms-item>
					<uni-forms-item label="制造商">
						<uni-easyinput v-model="form.manufacturer" placeholder="请输入制造商" class="iptBor" :inputBorder="false" />
					</uni-forms-item>
					<uni-forms-item label="供应商">
						<uni-easyinput v-model="form.supplier" placeholder="请输入供应商" class="iptBor" :inputBorder="false" />
					</uni-forms-item>
					<uni-forms-item label="设备型号">
						<uni-easyinput v-model="form.model" placeholder="请输入设备型号" class="iptBor" :inputBorder="false" />
					</uni-forms-item>
					<uni-forms-item label="采购日期">
						<view class="dateTimeBottom">
							<uni-datetime-picker type="date" placeholder="请选择采购日期" :clear-icon="false" v-model="form.purchase_date"
								:border="false" />
						</view>
					</uni-forms-item>
					<uni-forms-item label="保修到期日">
						<view class="dateTimeBottom">
							<uni-datetime-picker type="date" placeholder="请选择保修到期日" :clear-icon="false" v-model="form.warranty_date"
								:border="false" />
						</view>
					</uni-forms-item>
					<uni-forms-item label="启用日期">
						<view class="dateTimeBottom">
							<uni-datetime-picker type="date" placeholder="请选择启用日期" :clear-icon="false" v-model="form.use_start_date"
								:border="false" />
						</view>
					</uni-forms-item>
					<uni-forms-item label="采购价格">
						<uni-easyinput v-model="form.purchase_price" placeholder="请输入采购价格" class="iptBor" :inputBorder="false" />
					</uni-forms-item>
					<uni-forms-item label="安装地点">
						<uni-easyinput v-model="form.model" placeholder="请输入安装地点" class="iptBor" :inputBorder="false" />
					</uni-forms-item>
					<uni-forms-item label="使用状态">
						<uni-data-select v-model="form.status" :localdata="status_list" placeholder="请选择使用状态" mode="underline"
							:clear="false" />
					</uni-forms-item>
					<uni-forms-item label="备注">
						<uni-easyinput v-model="form.location" type="textarea" placeholder="请输入备注" />
					</uni-forms-item>
					<!-- <uni-forms-item label="附件">
						<uni-file-picker v-model="form.picture" file-mediatype="image" file-extname="png,jpg,jpeg" @select="select"
							return-type="object" title="只能上传jpg/png/jpeg文件，且建议大小不超过500kb"></uni-file-picker>
					</uni-forms-item> -->
					<u-button type="primary" text="提交" @click="save" />
				</uni-forms>
			</view>
		</view>
	</view>
</template>
<script setup>
import { reactive, ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app'
import deDeviceApi from '../../../api/device/de_list'
import { BASE_URL } from '../../../common/request';
import { generateCode } from '@/utils/index.js';

//页面标题
const pageInfo = reactive({
	navbarTitle: '设备档案',
	type: '',
	edit_id: null,
})

onLoad((option) => {
	get_classify_list()
	pageInfo.type = option.type
	if (option.type == 'edit') {
		pageInfo.navbarTitle = `${pageInfo.navbarTitle}(修改)`
		get_detail(option.id)
		pageInfo.edit_id = option.id
	} else {
		pageInfo.navbarTitle = `${pageInfo.navbarTitle}(新增)`
		form.code = generateCode('DE')
	}
})

const status_list = [
	{ text: '闲置', value: 1 },
	{ text: '运行中', value: 2 },
	{ text: '维修中', value: 3 },
	{ text: '已报废', value: 4 },
]

//自动生成按钮
const switchCode = ref(true);
function switchChange(v) {
	if (v) {
		form.code = generateCode('DE')
	}
}

const refForm = ref(null);
const form = reactive({
	code: '',
	name: '',
	classify: null,
	model: '',
	sn: '',
	manufacturer: '',
	supplier: '',
	purchase_date: null,
	warranty_date: null,
	use_start_date: null,
	purchase_price: 0,
	location: '',
	status: 2,
	desc: ''
});
const fields = Object.keys(form)
const rules = {
	code: { rules: [{ required: true, errorMessage: '请输入设备编号' }] },
	name: { rules: [{ required: true, errorMessage: '请输入设备名称' }] },
	classify: { rules: [{ required: true, errorMessage: '请选择职务' }] },
};

//详情
function get_detail(id) {
	deDeviceApi.device_detail(id).then(res => {
		const record = uni.$lodash.pick(res, fields) //过滤表单需要的字段
		// record.picture = {
		// 	name: 'file.txt',
		// 	extname: "txt",
		// 	url: res.picture,
		// }
		Object.assign(form, record)
	})
};

// 上传
const action = BASE_URL + '/file/';
const token = uni.getStorageSync("assecss_token");
function select({ tempFiles }) {
	uni.uploadFile({
		url: action, //
		filePath: tempFiles[0].path,
		name: 'file',
		header: {
			'Authorization': "JWT " + token
		},
		success: (files) => {
			const data = JSON.parse(files.data)
			form.picture = {
				name: 'file.txt',
				extname: "txt",
				url: data.file,
			}
		},
		fail: (err) => {
			uni.$u.toast('上传图片失败')
		}
	});
};
//提交表单
function save() {
	refForm.value.validate().then(() => {
		const params = uni.$lodash.cloneDeep(form) // 深拷贝一份form表单
		// params.picture = params.picture.url
		if (pageInfo.type == 'add') {
			deDeviceApi.post_device(params).then(res => {
				uni.$u.toast('添加成功')
				setTimeout(() => {
					backRefsh();
				}, 1000)
			})
		} else {
			//修改
			deDeviceApi.patch_device(params, pageInfo.edit_id).then((res) => {
				uni.$u.toast('修改成功')
				setTimeout(() => {
					backRefsh();
				}, 1000)
			})
		}
	}).catch((error) => {
		uni.$u.toast(error[0].errorMessage);
	})

}

const classify_list = ref([]);
function get_classify_list() {
	deDeviceApi.get_device_classify({ page: 1, page_size: 99999 }).then(res => {
		classify_list.value = res.results.map(v => ({
			text: v.name,
			value: v.id
		}))
	})
};

//返回上一级并刷新上一级页面
function backRefsh() {
	uni.navigateBack({
		delta: 1, // 返回的页面层数，1 表示返回上一级
		success: () => {
			uni.$bus.useBusEmit('de_list');
		}
	})
};
</script>

<style lang="scss" scoped></style>